package com.cal.utms.dao.maintenance;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.cal.utms.entity.CustodianContactPerson;
import com.cal.utms.entity.Fund;
import com.cal.utms.util.HibernateUtil;

public class CustodianContactPersonDao {
	
	public Object add(CustodianContactPerson ccp) {
		Object obj;
		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		System.out.println("Saving Custodian Contact Person "+ccp.getName());
		try {
			tx = session.beginTransaction();
			obj = session.save(ccp);
			tx.commit();
			System.out.println("Custodian Contact Person saved");
		} catch (Exception ex) {
			tx.rollback();
			obj = new Object();
			System.out.println("Exception in saving Custodian Contact Person "
					+ ex.getMessage());
			ex.printStackTrace();
		} finally {
			session.close();
		}
		return obj;
	}
	
	public void delete(CustodianContactPerson ccp) {

		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		//System.out.println("Deleting Custodian Contact Person "+ccp.getName());
		try {
			tx = session.beginTransaction();
			session.delete(ccp);
			tx.commit();
			System.out.println("Custodian Contact Person ");
		} catch (Exception ex) {
			tx.rollback();
			//System.out.println("Exception in saving Custodian Contact Person "+ ex.getMessage());
			ex.printStackTrace();
		} finally {
			session.close();
		}

	}
	
	
	@SuppressWarnings("unchecked")
	public List<CustodianContactPerson> getCustodianContactPersonsByFund(Fund fund ) {
		Session session = HibernateUtil.getSession().openSession();
		Transaction tx = null;
		List<CustodianContactPerson> ccpList = null;
		try {
			tx = session.beginTransaction();
			Query query =  session.createQuery("select c from CustodianContactPerson c where c.fund.id = :fundId");
			query.setParameter("fundId", fund.getId());
			ccpList =query.list();
			tx.commit();
		} catch (Exception e) {
			if (tx != null)
				tx.rollback();
			System.out.println("Exception getCustodianContactPersons " + e.getMessage());
			e.printStackTrace();
		} finally {
			session.close();
		}
		return ccpList;
	}
	
	public static void main(String[] args) {
		CustodianContactPersonDao ccdo = new CustodianContactPersonDao();
		/*Fund fund = new Fund();
		fund.setId(18);
		CustodianContactPersonDao ccdo = new CustodianContactPersonDao();
		List<CustodianContactPerson> ccpList = ccdo.getCustodianContactPersonsByFund(fund);
		for(CustodianContactPerson ccp:ccpList){
			System.out.println(ccp.getName());
		}
		*/
		
		CustodianContactPerson ccp = new CustodianContactPerson();
		ccp.setId(10);
		ccdo.delete(ccp);
	}

}
